package leeon.towthree;

import ipworks.IPWorksException;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TooManyListenersException;

import leeon.forpeddy.download.HtmlDownloader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LogTxtHelper {
	
	public static final String HTTP_URL = "http://10.64.130.23:81/log.txt";
	
	public static final String START_END = "---------------------------------------";
	
	private static Log logger = LogFactory.getLog(LogTxtHelper.class);
	
	private HtmlDownloader http;
	private List<LogObject> list;
	
	public LogTxtHelper() throws IPWorksException, TooManyListenersException {
		 http = new HtmlDownloader();
	}
	
	public void executeOneTime() {
		String log = getLog();
		list = new ArrayList<LogObject>();
		parseLog(log);
		LogDBHelper.updateLog(list);
	}
	
	public String getLog() {
		http.start(HTTP_URL);
		return http.contentToString();
	}
	
	public List<LogObject> getList() {
		return list;
	}
	
	public void parseLog(String log) {
		if (log == null || log.trim().length() == 0) return;
		
		int e = 0;
		int s = 0;
		while ((s = log.indexOf(START_END, e)) != -1) {
			e = log.indexOf(START_END, s+START_END.length());
			
			//完整的包含
			if (e != -1) {
				e += START_END.length();
				String one = log.substring(s, e);
				try {
					list.add(parseOne(one));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			//错误格式的log
			} else {
				logger.error(log);
				break;
			}
		}
		
	}
	
	public LogObject parseOne(String one) throws IOException {
		logger.debug("one log:[" + one + "]");
		
		LineNumberReader reader = new LineNumberReader(new StringReader(one));
		LogObject log = new LogObject();
		String line = null;
		while ((line = reader.readLine()) != null) {
			int n = reader.getLineNumber();
			if (n == 2) {
				log.setPushDate(line.trim());
			} else if (n == 5) {
				log.setFileName(line.trim().substring(13));
				log.setFileDate(line.trim().substring(1, 12));
			} else if (n == 6) {
				log.setFtpAddress(line.trim());
			} else if (n == 7) {
				log.setFtpPort(line.trim());
			} else if (n == 8) {
				log.setFtpUser(line.trim());
			} else if (n == 9) {
				log.setFtpPassword(line.trim());
			} else if (n == 10) {
				log.setFtpPath(line.trim());
			}
		}
		reader.close();
		return log;
	}
	
	/**
	 * @param args
	 * @throws TooManyListenersException 
	 * @throws IPWorksException 
	 */
	public static void main(String[] args) throws IPWorksException, TooManyListenersException {
		LogTxtHelper h = new LogTxtHelper();
		h.executeOneTime();
	}

}
